package org.standard.base.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import org.standard.base.model.BaseRole;
import org.standard.base.model.BaseUser;
import org.standard.base.service.BaseRoleService;
import org.standard.commons.utils.DAO;

public class BaseRoleServiceImpl implements BaseRoleService {
	private DAO dao;
	private static final char SUCCESS = '1';
	private static final char FAIL = '0';
	private static final char FAIL_1 = '2';
	private static final char FAIL_2 = '3';
	
	public DAO getDao() {
		return dao;
	}

	public void setDao(DAO dao) {
		this.dao = dao;
	}

	@Override
	public char createRole(BaseRole baseRole) {
		
		String hql = "from BaseRole where roleName = '"+baseRole.getRoleName()+"'";
		List list = dao.find(hql);
		if(list.size() == 0){
			dao.save(baseRole);
			return SUCCESS;
		}else{
			return FAIL;
		}
	}

	@Override
	public char modifyRole(BaseRole baseRole) {
		String hql = "from BaseRole where roleName = '"+baseRole.getRoleName()+"' and roleId != '"+baseRole.getRoleId()+"'";
		List list = dao.find(hql);
		if(list.size() == 0){
			dao.update(baseRole);
			return SUCCESS;
		}else{
			return FAIL;
		}
	}

	@Override
	public char deleteRole(BaseRole baseRole) {
		//删除权限之前,先要把有这个权限的用户的权限制空
		String hql = "from BaseUser where roleIdOther like '%"+baseRole.getRoleId()+"%' or roleId = '"+baseRole.getRoleId()+"'";
		List<BaseUser> users = dao.find(hql);
		if(users.size() >0 ){
			for(BaseUser user:users){
				String roleIdOther = user.getRoleIdOther();
				String roleId = user.getRoleId();
				if(StringUtils.isNotBlank(roleIdOther) && roleIdOther.indexOf(baseRole.getRoleId()) != -1){
					String[] temp = roleIdOther.split(baseRole.getRoleId());
					user.setRoleIdOther(temp[0]+temp[1]);
				}
				if(StringUtils.isNotBlank(roleId) ){
					user.setRoleId("");
				}
			}
		}
		
		dao.delete(baseRole);
		return SUCCESS;
	}

	@Override
	public char modifyPermission(String roleId,String funcIdGroup) {
		
		BaseRole role = (BaseRole) dao.find(BaseRole.class, roleId);
		role.setFuncIdGroup(funcIdGroup);
		dao.update(role);
		
		return SUCCESS;
	}

	@Override
	public List<BaseRole> roleList() {
		String hql = "from BaseRole where 1=1 order by roleOrder";
		List<BaseRole> roles = dao.find(hql);
		return roles;
	}

	@Override
	public BaseRole findByRoleId(String roleId) {
		// TODO Auto-generated method stub
		BaseRole role = new BaseRole();
		
		role = (BaseRole)dao.find(BaseRole.class, roleId);
		return role;
	}

}
